package com.jdyfy.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdyfy.entity.Menu;
import com.jdyfy.mapper.MenuMapper;
import com.jdyfy.service.MenuService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Override
    public List<Menu> findMenus() {

         // 查询所有菜单
        List<Menu> list = list();
        // 找出一级菜单
        //找出pid为null的菜单，作为一级菜单
        List<Menu> parentNodes = list.stream().filter(menu -> menu.getPid() == null).collect(Collectors.toList());
        // 递归设置子菜单
        for (Menu menu : parentNodes) {
            // 调用递归方法获取子菜单
            menu.setChildren(getChildren(menu, list));
        }
        return parentNodes;
    }

    /**
     * 递归查找子菜单
     *
     * @param parent 父级菜单
     * @param allMenus 所有菜单列表
     * @return 子菜单列表
     */
    private List<Menu> getChildren(Menu parent, List<Menu> allMenus) {
        // 查找当前父级菜单的直接子菜单
        List<Menu> children = allMenus.stream()
            .filter(menu -> parent.getMenuId().equals(menu.getPid()))
            .collect(Collectors.toList());

        // 对每个子菜单继续递归查找其子菜单
        for (Menu child : children) {
            child.setChildren(getChildren(child, allMenus));
        }

        return children;
    }
}
